#include "hikari.h"

bool isSameRegion(NavmeshRegion*lastRegion, float x, float z){
	return lastRegion->pointInNavmesh(x,z);
}

void processEnterInNewRegion(HikariContext*context, NavmeshRegion**lastNavmeshRegion, int&lastNavmeshX, int&lastNavmeshY, float x, float y){
	NavmeshRegion*region=context->getNavmeshManager()->getRegion(x, y);
	if(region==NULL){
		return;
	}
	int indx=0;
	int indy=0;
	region->getIndexOfCell(x,y,indx, indy);
	Cell*cell=region->getCell(indx,indy);
	if(cell!=NULL){
		(*lastNavmeshRegion)=region;
		region->getIndexOfCell(x, y, lastNavmeshX, lastNavmeshY);
		cell->addObstacle();
	}
}

void processLeaveRegion(NavmeshRegion**lastNavmeshRegion, int&lastNavmeshX, int&lastNavmeshY, float x, float y){
	Cell*cell=(*lastNavmeshRegion)->getCell(lastNavmeshX, lastNavmeshY);
	if(cell!=NULL){
		lastNavmeshX=-1;
		lastNavmeshY=-1;
		(*lastNavmeshRegion)=NULL;
		cell->removeObstacle();
	}
}

void PathFindAgentHComponent::update(HikariContext*context, HObj*object){
	vector3df position=object->getPosition();
	float x=position.X;
	float y=position.Z;
	//check if agent didn't move out from navmesh region
	if(lastNavmeshRegion!=NULL && lastNavmeshX!=-1 && lastNavmeshY!=-1){
		if(isSameRegion(lastNavmeshRegion, x, y)){
			int tX=0;
			int tY=0;
			lastNavmeshRegion->getIndexOfCell(x,y,tX, tY);
			//we hope, that agent did not move from last cell
			if(tX==lastNavmeshX && tY==lastNavmeshY){
				//do nothing
			}else{
				lastNavmeshRegion->getCell(lastNavmeshX, lastNavmeshY)->removeObstacle();
				int indx = 0, indy = 0;
				lastNavmeshRegion->getIndexOfCell(x,y,indx, indy);
				Cell*cell=lastNavmeshRegion->getCell(indx, indy);
				if(cell!=NULL){
					lastNavmeshX=tX;
					lastNavmeshY=tY;
					cell->addObstacle();
				}
			}
		}else{
			processLeaveRegion(&lastNavmeshRegion, lastNavmeshX, lastNavmeshY, x, y);
			processEnterInNewRegion(context, &lastNavmeshRegion, lastNavmeshX, lastNavmeshY, x,y);
		}
	}else{
		processEnterInNewRegion(context, &lastNavmeshRegion, lastNavmeshX, lastNavmeshY, x,y);
	}
}

void PathFindAgentHComponent::onSceneLoad(HikariContext*context, HObj*object){
	
}

void PathFindAgentHComponent::onSceneUnload(HikariContext*context, HObj*object){

}

void PathFindAgentHComponent::onRender(HikariContext*context, HObj*object){

}